package com.greak.netty_stude.length;

import io.netty.util.concurrent.DefaultEventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;

/**
 * Created on 2021/1/26.
 *
 * @author Alan
 * @since 1.0
 */
public class ChannelPromiseExample extends Thread {

    private static final Object object = new Object();

    public static void main(String[] args) {
        final DefaultEventExecutor executor = new DefaultEventExecutor();
        final Promise<Integer> promise = executor.newPromise();

        // 任务seccess或者failure来回调operationComplete 方法
        promise.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future)
                    throws Exception {
                System.out.println(Thread.currentThread().getName() + " 第一个监听器");
                if (future.isSuccess()) {
                    System.out.println("任务成功，result：" + future.get());
                } else {
                    System.out.println("任务失败，result：" + future.cause());
                }
            }
        }).addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future)
                    throws Exception {
                System.out.println(Thread.currentThread().getName() + " 第二个监听器");
            }
        });
        // 提交任务
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //可以设置成功或者失败
                promise.setSuccess(1);
//                promise.setFailure(new Throwable("FAILURE"));
            }
        });


        try {
            System.out.println("promise wait begin");
            promise.sync();
//            promise.await();
            System.out.println("promise wait end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}
